﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.WebControls;
using Rezepto.Account;
using Rezepto.DatenbankObjekte;
using Rezepto.DatenbankVerbindung;
using Rezepto.Enum;
using System.IO;

namespace Rezepto
{
    public partial class RezeptEingabe : LoginPage
    {
        public int numOfRows = 5;

        protected void Page_Init(object sender, EventArgs e)
        {
            GenerateTable(numOfRows);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if(IsLoggedIn()!=null)
                {
                    ForbiddenArea.Visible = false;
                    RezeptEingabeArea.Visible = true;
                }
                KategorieList.DataSource = CreateKategorieDataSource();
                KategorieList.DataTextField = "KatTextField";
                KategorieList.DataTextField = "KatValueField";
                KategorieList.DataBind();
                KategorieList.SelectedIndex = 0;
            }

        }

        public void OnSave(object sender, EventArgs e)
        {
            String errorText="";
            var rName = RezeptName.Text;
            if (rName.Equals(""))
                errorText = "Bitte geben Sie einen Rezeptnamen ein <br>";
            var kategorieId = KategorieList.SelectedIndex;
            var bild = FileUpload.FileBytes;
            var beschreibungString = Beschreibung.Text;
            if (beschreibungString.Equals(""))
                errorText += "Bitte geben Sie einen Zubereitungstext an <br>";
            String zutatErr = "";
            List < Zutat > zutaten= getZutaten(out zutatErr);
            if (zutaten == null || zutaten.Count == 0)
                errorText += zutatErr;
            Decimal kalorienString;
            if (!Decimal.TryParse(Kalorien.Text, out kalorienString))
                errorText += "Bitte Kalorienanzahl eingeben <br>";
            //var kalorienString = Convert.ToDecimal(Kalorien.Text);
            var rezeptId = OracleVerbindung.GetNextSequenceForTable("REZEPT");
            var zutatId = OracleVerbindung.GetNextSequenceForTable("ZUTAT");
            var bildId = OracleVerbindung.GetNextSequenceForTable("BILD");
            var userId = IsLoggedIn().Id;
            if(!errorText.Equals(""))
                errorLabel.Text = errorText;
            else
            {
                OracleVerbindung.SpeicherRezept(kategorieId, bild, beschreibungString, zutaten, kalorienString, rezeptId, zutatId, userId, rName, bildId);
                Response.Redirect("Default.aspx?rezeptid=" + rezeptId);
            }

        }
        public List<Zutat> getZutaten(out String error)
        {
            int rowsCount = numOfRows;
            int colsCount = 3;
            error = String.Empty;
            List<Zutat> zList = new List<Zutat>();
            for (int i = 0; i < rowsCount; i++)
            {
                Zutat z = new Zutat();
                for (int j = 0; j < colsCount; j++)
                {
                    if (!Request.Form["ctl00$MainContent$TextBoxRow_" + i + "Col_0"].ToString().Equals("") && !Request.Form["ctl00$MainContent$TextBoxRow_" + i + "Col_2"].ToString().Equals(""))
                    {
                        if (j == 0)
                        {
                            Decimal menge;
                            if (!Decimal.TryParse(Request.Form["ctl00$MainContent$TextBoxRow_" + i + "Col_" + j], out menge))
                            {
                                error += "Zutatenmenge ist keine Zahl <br>";
                                return null;
                            }
                            z.Menge = menge;
                        }
                        else if (j == 1)
                            z.Einheit = Request.Form["ctl00$MainContent$TextBoxRow_" + i + "Col_" + j];
                        else if (j == 2)
                            z.ZutatName = Request.Form["ctl00$MainContent$TextBoxRow_" + i + "Col_" + j];
                    }
                    else
                    {
                        continue;
                    }
                }
                if(z.Menge != 0)
                    zList.Add(z);
            }
            if (zList.Count == 0)
                error += "Es wurden keine Zutaten eingegeben <br>";
            return zList;
        }

        ICollection CreateUnitDataSource()
        {//DataSource eventuell aus der Datenbank lesen
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("UnitTextField", typeof(String)));
            dt.Columns.Add(new DataColumn("UnitValueField", typeof(String)));

            dt.Rows.Add(CreateRow("g", "g", dt));
            dt.Rows.Add(CreateRow("ml", "ml", dt));
            dt.Rows.Add(CreateRow("Prise", "Prise", dt));
            dt.Rows.Add(CreateRow("Stück", "Stück", dt));
            dt.Rows.Add(CreateRow("Esslöffel", "Esslöffel", dt));
            dt.Rows.Add(CreateRow("Teelöffel", "Teelöffel", dt));

            DataView dv = new DataView(dt);
            return dv;
        }
        ICollection CreateKategorieDataSource()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add(new DataColumn("KatTextField", typeof (String)));
            dt.Columns.Add(new DataColumn("KatValueField", typeof(String)));

            dt.Rows.Add(CreateRow(0.ToString(),Kategorie.Vorspeise.ToString(), dt));
            dt.Rows.Add(CreateRow(1.ToString(), Kategorie.Hauptspeise.ToString(), dt));
            dt.Rows.Add(CreateRow(2.ToString(), Kategorie.Nachspeise.ToString(), dt));

            DataView dv = new DataView(dt);
            return dv;
        }

        DataRow CreateRow(String Text, String Value, DataTable dt)
        {
            DataRow dr = dt.NewRow();
            dr[0] = Text;
            dr[1] = Value;

            return dr;
        }
        private void GenerateTable(int rowsCount)
        {
            ZutatenTable.Controls.Clear();
            Table table = ZutatenTable;
            TableHeaderRow th = new TableHeaderRow();
            th.Cells.Add(new TableHeaderCell{Text = "Menge"});
            th.Cells.Add(new TableHeaderCell {Text = "Einheit"});
            th.Cells.Add(new TableHeaderCell { Text = "Zutat" });
            table.Rows.Add(th);
            if (table == null)
            {
                table = new Table();
                table.ID = "ZutatenTable";
                Master.FindControl("MainContent").FindControl("ZutatenTabPlaceHolder").Controls.Add(table);
            }

            
            //The number of Columns to be generated
            const int colsCount = 3;//You can changed the value of 3 based on you requirements

            // Now iterate through the table and add your controls

            for (int i = 0; i < rowsCount; i++)
            {
                TableRow row = new TableRow();
                for (int j = 0; j < colsCount; j++)
                {
                    TableCell cell = new TableCell();
                    if(j!=1)
                    {
                        TextBox tb = new TextBox();

                        // Set a unique ID for each TextBox added
                        tb.ID = "TextBoxRow_" + i + "Col_" + j;
                        // Add the control to the TableCell
                        cell.Controls.Add(tb);
                        // Add the TableCell to the TableRow
                        row.Cells.Add(cell);
                    }
                    else
                    {
                        DropDownList ddl = new DropDownList();
                        ddl.ID = "TextBoxRow_" + i + "Col_" + j;
                        ddl.DataSource = CreateUnitDataSource();
                        ddl.DataTextField = "UnitTextField";
                        ddl.DataValueField = "UnitValueField";
                        ddl.DataBind();
                        ddl.SelectedIndex = 0;
                        cell.Controls.Add(ddl);
                        row.Cells.Add(cell);
                    }

                }

                // And finally, add the TableRow to the Table
                table.Rows.Add(row);
            }

            //Set Previous Data on PostBacks
            SetPreviousData(rowsCount, colsCount);

            //Sore the current Rows Count in ViewState
            rowsCount++;
            ViewState["RowsCount"] = rowsCount;


        }

        private void SetPreviousData(int rowsCount, int colsCount)
        {
            Table table = (Table)Master.FindControl("MainContent").FindControl("ZutatenTabPlaceHolder").Controls[0];
            if (table != null)
            {
                for (int i = 0; i < rowsCount; i++)
                {
                    for (int j = 0; j < colsCount; j++)
                    {
                        if(j!=1)
                        {
                            //Extracting the Dynamic Controls from the Table
                            TextBox tb = (TextBox)table.Rows[i].Cells[j].FindControl("TextBoxRow_" + i + "Col_" + j);
                            //Use Request objects for getting the previous data of the dynamic textbox
                            tb.Text = Request.Form["ctl00$MainContent$TextBoxRow_"+ i +"Col_"+ j];
                            
                        }
                        else
                        {
                            DropDownList ddl = (DropDownList)table.Rows[i].Cells[j].FindControl("TextBoxRow_" + i + "Col_" + j);
                            ddl.Text = Request.Form["ctl00$MainContent$TextBoxRow_" + i + "Col_" + j];
                        }

                    }
                }
            }
        }
        protected void addRow(object sender, EventArgs e)
        {
            if (ViewState["RowsCount"] != null)
            {
                numOfRows = Convert.ToInt32(ViewState["RowsCount"].ToString());
                GenerateTable(numOfRows);
                //addDropdownValues();
            }
 
        }
    }
}